import 'dart:async';
import 'dart:math' as math;

import 'package:dotted_border/dotted_border.dart';
import 'package:flutter/material.dart';
import 'package:flutter_compass/flutter_compass.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_unionad/flutter_unionad.dart';
import 'package:geomancy/api/geomancy.dart';
import 'package:geomancy/enums/index.dart';
import 'package:geomancy/models/base_model.dart';
import 'package:geomancy/providers/user_provider.dart';
import 'package:geomancy/styles/index.dart';
import 'package:geomancy/tools/constant.dart';
import 'package:geomancy/tools/event.dart';
import 'package:geomancy/tools/utils.dart';
import 'package:geomancy/widgets/common_btn.dart';
import 'package:geomancy/widgets/common_circle_btn.dart';
import 'package:geomancy/widgets/common_header.dart';
import 'package:geomancy/widgets/common_loading_circle.dart';
import 'package:geomancy/widgets/common_text.dart';
import 'package:geomancy/widgets/modal_util/index.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';

class StartCompassPage extends StatefulWidget {
  final CompassSource source;
  final String? birthday;
  final String? sex;
  const StartCompassPage({super.key, required this.source, this.birthday, this.sex});

  @override
  State<StartCompassPage> createState() => _StartCompassPageState();
}

class _StartCompassPageState extends State<StartCompassPage> {
  StreamSubscription? _adViewStream;
  bool _canRotate = true;
  String towards = '正南';
  String sit = '正北';
  double currentDirection = 0.00;
  late String requestType;
  //广告验证是否成功
  bool adRewardVerify = false;

  @override
  void initState() {
    super.initState();
    requestType = compassSourceValues[widget.source]!;
    _adViewStream = FlutterUnionadStream.initAdStream(
      flutterUnionadRewardAdCallBack: FlutterUnionadRewardAdCallBack(
        onShow: () {
          debugPrint("激励广告显示");
        }, onClick: () {
        debugPrint("激励广告点击");
      }, onFail: (error) {
        debugPrint("激励广告失败 $error");
      }, onClose: () {
        debugPrint("激励广告关闭");
        if (adRewardVerify) {
          context.pop();
          showADSuccessModal();
        }
      }, onSkip: () {
        debugPrint("激励广告跳过");
      }, onReady: () async {
        debugPrint("激励广告预加载准备就绪");
        await FlutterUnionad.showRewardVideoAd();
      }, onCache: () async {
        debugPrint("激励广告物料缓存成功。建议在这里进行广告展示，可保证播放流畅和展示流畅，用户体验更好。");
      }, onUnReady: () {
        debugPrint("激励广告预加载未准备就绪");
      }, onVerify: (rewardVerify, rewardAmount, rewardName, errorCode, error) {
        debugPrint("激励广告奖励  验证结果=$rewardVerify 奖励=$rewardAmount  奖励名称$rewardName 错误码=$errorCode 错误$error");
      }, onRewardArrived: (rewardVerify, rewardType, rewardAmount, rewardName, errorCode, error, propose) {
        adRewardVerify = rewardVerify;
        debugPrint("阶段激励广告奖励  验证结果=$rewardVerify 奖励类型<FlutterUnionadRewardType>=$rewardType 奖励=$rewardAmount"
                "奖励名称$rewardName 错误码=$errorCode 错误$error 建议奖励$propose");
      }),
    );
  }
  @override
  void dispose() {
    if (_adViewStream != null) {
      _adViewStream?.cancel();
    }
    super.dispose();
  }

  ///广告提示弹窗
  showADTipsModal() {
    ModalUtil.showBlurGeneralDialogWidget(
      context: context,
      modalWidget: Center(
        child: DottedBorder(
          borderType: BorderType.RRect,
          strokeWidth: 5.w,
          radius: Radius.circular(60.w),
          dashPattern: [12.w, 6.w],
          color: ColorStyle.borderColor,
          child: Container(
            width: 500.w,
            height: 400.w,
            padding: EdgeInsets.only(top: 70.w, bottom: 65.w),
            decoration: BoxDecoration(
                color: ColorStyle.themeLightColor,
                borderRadius: BorderRadius.all(Radius.circular(60.w))
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                const CommonText(txt: '(观看广告并获得一次机会)'),
                CommonBtnWidget(active: false, size: Size(390.w, 80.w), onTap: loadRewardVideoAd, child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Image.asset('assets/icons/icon_view_ad.png', height: 35.w),
                    SizedBox(width: 10.w),
                    const CommonText(txt: '获得(1/1)')
                  ],
                )),
                CommonBtnWidget(txt: '不，谢谢', size: Size(390.w, 80.w), onTap: () {
                  context.pop();
                }),
              ],
            ),
          )
        ),
      ),
    );
  }
  ///观看完广告提示弹窗
  showADSuccessModal() {
    ModalUtil.showBlurGeneralDialogWidget(
      context: context,
      barrierDismissible: true,
      modalWidget: Center(
        child: Container(
          decoration: BoxDecoration(
            color: ColorStyle.themeLightColor,
            borderRadius: BorderRadius.all(Radius.circular(60.w))
          ),
          child: DottedBorder(
              borderType: BorderType.RRect,
              strokeWidth: 5.w,
              radius: Radius.circular(60.w),
              dashPattern: [12.w, 6.w],
              color: ColorStyle.borderColor,
              child: Container(
                width: 390.w,
                height: 200.w,
                padding: EdgeInsets.symmetric(vertical: 34.w),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Image.asset('assets/icons/icon_smil.png', width: 72.w,),
                    CommonText(txt: '使用次数+1', fontSize: 36.sp),
                  ],
                ),
              )
          ),
        ),
      )
    );
  }

  ///朝向
  String getCompassDirection(double direction) {
    // 将 direction 限制在 0° - 360° 范围内
    direction = direction % 360;

    if (direction < 22.5 || direction >= 337.5) {
      return '正北';
    } else if (direction >= 22.5 && direction < 67.5) {
      return '东北';
    } else if (direction >= 67.5 && direction < 112.5) {
      return '正东';
    } else if (direction >= 112.5 && direction < 157.5) {
      return '东南';
    } else if (direction >= 157.5 && direction < 202.5) {
      return '正南';
    } else if (direction >= 202.5 && direction < 247.5) {
      return '西南';
    } else if (direction >= 247.5 && direction < 292.5) {
      return '正西';
    } else {
      return '西北';
    }
  }
  ///坐向
  String getSeatingDirection(double direction) {
    // 坐向是朝向的反方向（+180°）
    double seatingDirection = (direction + 180) % 360;
    return getCompassDirection(seatingDirection);
  }

  ///锁定
  lockOnTapHandle() {
    Utils.shake();
    setState(() {
      _canRotate = !_canRotate;
    });
  }
  ///预加载激励广告
  loadRewardVideoAd() async {
    final user = context.read<UserProvider>().getUserInfo;
    FlutterUnionad.loadRewardVideoAd(
      //Android 激励视频广告id  必填
      androidCodeId: "962823263",
      //ios 激励视频广告id  必填
      iosCodeId: "962823263",
      //奖励名称 选填
      rewardName: "堪舆次数+1",
      //奖励数量 选填
      rewardAmount: 1,
      //  用户id 选填
      userID: user?.id?.toString() ?? '',
      //视屏方向 选填
      orientation: FlutterUnionadOrientation.VERTICAL,
      //扩展参数 选填
      mediaExtra: user?.id.toString(),
    );
  }
  ///新增堪舆记录
  Future addRecord() async {
    try {
      GeomancyAddAPIData params = GeomancyAddAPIData(
        type: requestType,
        deg: currentDirection.toString(),
        birthday: widget.birthday,
        sex: widget.sex,
      );
      final result = await GeomancyAPI.addRecord(context: context, params: params);
      if (result?.code == 200) {
        eventListener.emit(Constant.REFRESHRECORDLIST);
        return result!.data;
      } else if (result?.code == 400) {///次数用完了,看视频增加次数
        showADTipsModal();
      }
    } catch(e) {
      return null;
    }
  }
  ///下一步
  Future nextOnTapHandle() async {
    Utils.shake();
    if (_canRotate) {
      EasyLoading.showToast('请先锁定罗盘');
      return;
    }
    final int? recordId = await addRecord();
    if (recordId == null || !mounted) {
      return;
    }
    switch (widget.source) {
      case CompassSource.health:
        context.push('/health_result', extra: {
          "source": widget.source,
          "direction": currentDirection,
          "birthday": widget.birthday,
          "sex": widget.sex
        });
        break;
      case CompassSource.roomWealth:
      case CompassSource.stationWealth:
        context.push('/wealth_result', extra: {
          "source": widget.source,
          "direction": currentDirection
        });
        break;
      case CompassSource.roomStudy:
      case CompassSource.stationStudy:
        context.push('/study_result', extra: {
          "source": widget.source,
          "direction": currentDirection,
          "birthday": widget.birthday,
        });
        break;
      case CompassSource.roomRelations:
      case CompassSource.stationRelations:
        context.push('/relations_result', extra: {
          "source": widget.source,
          "direction": currentDirection,
          "birthday": widget.birthday,
        });
        break;
      default:
        break;
    }
  }

  @override
  Widget build(BuildContext context) {
    String formattedDirection = currentDirection.abs().toStringAsFixed(2);
    return Scaffold(
      appBar: CommonHeader.appBar(context: context),
      backgroundColor: ColorStyle.pageDefaultColor,
      body: SafeArea(
        child: Container(
          width: double.infinity,
          padding: EdgeInsets.fromLTRB(Constant.PAGEPADDING.w, 20.w, Constant.PAGEPADDING.w, Constant.PAGEPADDING.w),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              ///朝向
              Container(
                width: 280.w,
                height: 130.w,
                decoration: BoxDecoration(
                    color: ColorStyle.themeColor,
                    border: Border.all(width: 6.w, color: ColorStyle.borderColor),
                    borderRadius: BorderRadius.all(Radius.circular(65.w))
                ),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Container(
                      height: 57.5.w,
                      alignment: Alignment.center,
                      child: CommonText(txt: '朝向 : $towards', fontSize: 36.sp),
                    ),
                    Container(
                      width: double.infinity,
                      height: 3.w,
                      color: ColorStyle.borderColor,
                    ),
                    Container(
                      height: 57.5.w,
                      alignment: Alignment.center,
                      child: CommonText(txt: '$formattedDirection°'),
                    ),
                  ],
                ),
              ),
              Expanded(child: Stack(
                children: [
                  ///罗盘
                  StreamBuilder<CompassEvent>(
                    stream: FlutterCompass.events,
                    builder: (context, snapshot) {
                      if (snapshot.hasError) {
                        return CommonText(txt: '错误：${snapshot.error}');
                      }
                      if (snapshot.connectionState == ConnectionState.waiting) {
                        return const Center(
                          child: CommonLoadingCircleWidget(),
                        );
                      }
                      double? direction = snapshot.data!.heading;
                      if (direction == null) {
                        return const Center(
                          child: CommonText(txt: '设备无法使用指南针'),
                        );
                      }
                      Future.delayed(Duration.zero, () {
                        if (mounted && _canRotate) {
                          setState(() {
                            towards = getCompassDirection(direction);
                            sit = getSeatingDirection(direction);
                            currentDirection = direction;
                          });
                        }
                      });
                      ///图片是上南下北，所以需要 direction + 180
                      return Center(child: _canRotate ? Transform.rotate(
                        angle: ((direction + 180) * (math.pi / 180) * -1),
                        child: Image.asset('assets/icons/compass.png', width: 670.w, height: 670.w,)
                      ) : Transform.rotate(
                          angle: ((currentDirection + 180) * (math.pi / 180) * -1),
                          child: Image.asset('assets/icons/compass.png', width: 670.w, height: 670.w,)
                      ));
                    },
                  ),
                  ///指针
                  Positioned(
                    top: 4.w,
                    left: 0,
                    right: 0,
                    bottom: 44.w,
                    child: Center(child: SizedBox(
                      width: 28.w,
                      height: double.infinity,
                      child: Image.asset('assets/icons/compass_pointer.png', fit: BoxFit.fill),
                    )),
                    // child: Center(child: Image.asset('assets/icons/compass_pointer.png', height: 989.w)),
                  ),
                  ///锁定
                  Positioned(
                    left: 0,
                    bottom: 44.w,
                    child: CommonCircleBtnWidget(size: 130.w, txt: _canRotate ? '锁定' : '解锁', onTap: lockOnTapHandle),
                  ),
                  ///下一步
                  Positioned(
                    right: 0,
                    bottom: 44.w,
                    child: CommonCircleBtnWidget(size: 130.w, txt: '下一步', onTap: nextOnTapHandle),
                  )
                ],
              )),
              ///坐向
              Container(
                width: 280.w,
                height: 130.w,
                decoration: BoxDecoration(
                    color: ColorStyle.themeColor,
                    border: Border.all(width: 6.w, color: ColorStyle.borderColor),
                    borderRadius: BorderRadius.all(Radius.circular(65.w))
                ),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Container(
                      height: 57.5.w,
                      alignment: Alignment.center,
                      child: CommonText(txt: '坐向 : $sit', fontSize: 36.sp),
                    ),
                    Container(
                      width: double.infinity,
                      height: 3.w,
                      color: ColorStyle.borderColor,
                    ),
                    Container(
                      height: 57.5.w,
                      alignment: Alignment.center,
                      child: CommonText(txt: '${((360 - double.parse(formattedDirection)) % 360).toStringAsFixed(2)}°'),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
